import { Component } from '@angular/core';
import { AlertController, IonicPage, LoadingController, NavController, NavParams } from 'ionic-angular';
import { HttpServicesProvider } from "../../providers/http-services/http-services";
import { StorageProvider } from "../../providers/storage/storage";
import { ValidateProvider } from "../../providers/validate/validate";
import { UtilsProvider } from "../../providers/utils/utils";
import { UpperWordCasePipe } from "../../pipes/upper-word-case/upper-word-case";

@IonicPage({
    segment: 'login'
})
@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
})
export class LoginPage {
    userInfo = {
        username: '',
        head_img: '',
        code: ''
    };
    wxInfo = {};
    autoLogin = true;
    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public httpService: HttpServicesProvider,
        public storage: StorageProvider,
        public alertCtrl: AlertController,
        public validate: ValidateProvider,
        public util: UtilsProvider,
        public loadCtrl: LoadingController,
        public upperWord: UpperWordCasePipe
    )
    {
        if (this.autoLogin == false) {
            this.storage.set('tokenInfo', '{"token":"ODlhMWJqbG53bHZObGpEMjJOMkM2MDlXRlI2Lzg0U0F4UXMrVWpHVkpUMnc_c","timestamp":1588167942}');
            this.storage.set('wxInfo', '{"openid":"o3J-Q0m11Yj0JVIGyNyM3d98buhc","nickname":"乐之-","sex":1,"language":"zh_CN","city":"西安","province":"陕西","country":"中国","headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/UXHJn1yic5NfFummXg0jhbI0EVk9WPKXahGh9hHZNwoPzyxcodJDts5nj9UcuqwK1ib7ht0Vh28sicuInVnI2icjiag/132","privilege":[],"unionid":"otmRMv_9imslZ3s5KQyXyeA2fQMQ","reg_step":"2"}');
            this.storage.set('userInfo', '{"user_id":6907,"user_name":"15029213035","nickname":"乐之-","full_name":null,"head_img":"http://thirdwx.qlogo.cn/mmopen/vi_32/UXHJn1yic5NfFummXg0jhbI0EVk9WPKXahGh9hHZNwoPzyxcodJDts5nj9UcuqwK1ib7ht0Vh28sicuInVnI2icjiag/132"}');
        }
    }

    ionViewDidEnter() {
        let wxInfo = this.storage.get('wxInfo');
        if (wxInfo) {
            wxInfo = JSON.parse(wxInfo);
            this.userInfo.head_img = wxInfo['headimgurl'];
        }

    }

    ionViewDidLoad() {
        if (this.autoLogin === true) {
            if (!this.validate.checkLogin()) {
                let wxInfo = this.storage.get('wxInfo');
                if (wxInfo) {
                    wxInfo = JSON.parse(wxInfo);
                    this.validate.getToken(wxInfo['openid'], status => {
                        if (status) {
                            if (this.storage.get('shareData')) {
                                let shareData = JSON.parse(this.storage.get('shareData'));
                                this.navCtrl.setRoot('HomePage').then(() => {
                                    this.navCtrl.push(this.upperWord.transform(shareData['page']) + 'Page', shareData['data']);
                                    this.storage.remove('shareData');
                                });
                            } else {
                                location.href = location.href.split("#")[0].split('?')[0] + "?";

                            }
                        } else {
                            this.autoLogin = false;
                        }
                    });
                } else {
                    this.validate.getWxInfo(result => {
                        if (result) {
                            // location.href=location.href.split("#")[0].split('?')[0]+"?";

                            if (this.storage.get('shareData')) {
                                let shareData = JSON.parse(this.storage.get('shareData'));
                                this.navCtrl.setRoot('HomePage').then(() => {
                                    this.navCtrl.push(this.upperWord.transform(shareData['page']) + 'Page', shareData['data']);
                                    this.storage.remove('shareData');
                                });
                            } else {
                                this.navCtrl.setRoot('HomePage')
                            }
                        } else {
                            let wxInfo = this.storage.get('wxInfo');
                            if (wxInfo) {
                                wxInfo = JSON.parse(wxInfo);
                                this.userInfo.head_img = wxInfo['headimgurl'];
                            }
                            this.autoLogin = false;
                        }
                    });
                }
            } else {
                // location.href = location.href.split("#")[0].split('?')[0] + "?";
            }
        }

    }




    doLogin() {
        if (this.userInfo.code == '') {
            this.util.presentAlert('请输入验证码');
            return false;
        }
        if (this.userInfo.username == '') {
            this.util.presentAlert('请输入您的手机号');
            return false;
        }
        if (this.userInfo.username.length != 11) {
            this.util.presentAlert('手机号格式有误');
            return false;
        }

        let loader = this.loadCtrl.create({
            content: "正在登录，请稍后..."
        });
        loader.present();
        let wxInfo = this.storage.get('wxInfo');
        this.wxInfo = JSON.parse(wxInfo);
        this.userInfo['head_img'] = this.userInfo['head_img'] == '' ? this.wxInfo['head_img'] : this.userInfo['head_img'];
        let apiUrl = "/user/login_option";

        let postData = {
            openid: this.wxInfo['openid'],
            unionid: this.wxInfo['unionid'],
            nickname: this.wxInfo['nickname'],
            head_img: this.userInfo['head_img'],
            user_name: this.userInfo['username'],
            code: this.userInfo['code'],
            password: 123456
        };

        this.httpService.requestPostData(apiUrl, postData, data => {
            loader.dismiss();
            if (data['code'] == 200) {
                let tokenInfo = {
                    token: data['token'],
                    timestamp: this.util.getTime()
                };
                this.storage.set('tokenInfo', JSON.stringify(tokenInfo));
                this.validate.getUserInfo(() => { });
                this.navCtrl.pop();
                // this.util.presentAlert(
                //     '恭喜您，注册成功！'
                //     // ()=>{
                //     //     this.navCtrl.setRoot('HomePage').then(()=>{
                //     //         this.navCtrl.push('RegisterPage');
                //     //     });
                //     // },
                //     // ()=>{
                //     //     this.navCtrl.setRoot('HomePage')
                //     // }
                // );
                // this.navCtrl.setRoot('HomePage')
                let loginAlert = this.alertCtrl.create({
                    message: '恭喜您，注册成功！',
                    buttons: [
                        {
                            text: '知道了',
                            handler: () => {
                                this.navCtrl.setRoot('HomePage')
                            }
                        },
                    ]
                });
                loginAlert.present();

            } else {
                let alert = this.alertCtrl.create({
                    subTitle: data['message'],
                    buttons: ['确定']
                });
                alert.present();
            }
        })
    }
    
    uploadHeadImg(e) {
        let file = e.target.files[0];
        if (file == undefined) {
            return false;
        }
        let data = new FormData();
        data.append('image', file);
        data.append('type', 'headimg');
        this.httpService.uploadImage('/user/upload_file', data, result => {
            if (result.code == 200) {
                this.userInfo['head_img'] = result.img_path;
            } else {
                this.util.presentAlert('头像上传失败，请稍后再试');
            }
        });
    }

    clear() {
        this.storage.clear();
    }

    timer = {
        time: 60,
        start: false,
        text: '获取验证码'
    };
    getCode() {
        if (this.userInfo.username == '') {
            this.util.presentAlert('请输入您的手机号');
            return false;
        }
        this.timer.start = true;
        let t = setInterval(() => {
            this.timer.time--;
            this.timer.text = this.timer.time + "秒重新获取";
            if (this.timer.time <= 0) {
                clearTimeout(t);
                this.timer = {
                    time: 60,
                    start: false,
                    text: '重新获取'
                };
            }
        }, 1000);
        let apiUrl = "/user/getcode_option";
        this.httpService.requestPostData(apiUrl, { user_name: this.userInfo.username }, data => {
            if (data.error == 200) {
                let loader = this.loadCtrl.create({
                    content: "验证码已发送",
                    duration: 2000
                });
                loader.present();
            } else {
                this.util.presentAlert(data.message);
            }
        })
    }

}
